package com.xbstar.web;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.xbstar.bean.UserInfo;
import com.xbstar.bean.WeiUserInfo;
import com.xbstar.dao.UserInfoRepository;
import com.xbstar.dao.WeiUserInfoRepository;
import com.xbstar.tools.BeanUtils;
import com.xbstar.tools.JFUserAuthentication;
import com.xbstar.wei.service2.Message.Access_Token;
import com.xbstar.wei.service2.WeixinUtil;


@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserInfoRepository userDao;
	@Autowired
	private WeiUserInfoRepository weiUserInfoDao;
	@RequestMapping("/login")
	@ResponseBody
	public String login(@RequestParam("userId") String loginkey1, @RequestParam ( "userPassword" ) String pwd){
		UserInfo user=null;
		
		try {
			System.out.println(JFUserAuthentication.decryptBASE64(loginkey1));
			System.out.println(pwd);
			Long loginkey =Long.parseLong(JFUserAuthentication.decryptBASE64(loginkey1));
			user=userDao.findOne(loginkey-10000);
		} catch (Exception e) {
			System.out.println();
		}
		System.out.println(user.getPwd());
		JSONObject result=new JSONObject();
		if(user!=null&&user.getPwd().equals(pwd)){
			
			result.put(UserPackage.TICKET, JFUserAuthentication.getAticket(user.getId().toString()));
			result.put(UserPackage.STATUS, "200");
		}else{
			result.put("status", "401");
		}
		return  result.toString();
	}
	
	@RequestMapping("/regist")
	public String regist(@RequestParam("name")String name,@RequestParam("pwd") String pwd){
		UserInfo newUser=null;
		UserInfo user=new UserInfo();
		try {
			user.setName(JFUserAuthentication.decryptBASE64(name));
			user.setPwd(pwd);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		JSONObject result=new JSONObject();
		if(user!=null){
			try {
				newUser=userDao.save(user);
			} catch (Exception e) {
				System.out.println("注册新用户出错：");
				e.printStackTrace();
			}
			if(newUser!=null){
				result.put(UserPackage.STATUS, "200");
				JSONObject result1=new JSONObject();
				result1.put("loginid", newUser.getId()+10000);
				result.put(UserPackage.DATA, result1);
			}else{
				result.put("status", "500");
			}
		}
//		UserInfo user=new UserInfo();
//		user.setPwd("123456");
//		user.setName("xiaoji");
//		UserService us=new UserService();
//		us.registUser(user);
		//String ss=JFUserAuthentication.getLoginKeyFromRequest(ticket);
		return result.toString();
	}
	@RequestMapping("/wei")
	public String weiLogin(HttpServletRequest req){
		String code=req.getParameter(Access_Token.Code);
		String state=req.getParameter(Access_Token.State);
		JSONObject result=new JSONObject();
		if(code==null||state==null||state.equals("123")){
			result.put(UserPackage.STATUS, UserPackage.LOST_PARAM);
		}else{
			WeixinUtil wxu=new WeixinUtil();
			try {
				JSONObject tsjon=wxu.getAcessTokenJsonByCode(code);
				JSONObject userjson=wxu.getUserInfoFromWeiByAccessTokenAndOpenid(tsjon.getString(Access_Token.Access_token), tsjon.getString(Access_Token.Openid));
				WeiUserInfo wui=new WeiUserInfo(userjson);
				String userId=null;
				WeiUserInfo tui=weiUserInfoDao.findOne(wui.getOpenId());
				List<UserInfo>sssd=new ArrayList<>();
				if(tui!=null){
					sssd=userDao.findByOpenid(tui.getOpenId());
				}
				
				JSONObject jsson=BeanUtils.getAJsonFromObj(wui, null);
				if(tui==null||sssd.size()==0||tui==null||tui.getNickName()==null){
					//说明未曾登录
					weiUserInfoDao.save(wui);
					UserInfo newUser=new UserInfo();
					newUser.setPwd("123456");
					newUser.setOpenid(wui.getOpenId());
					newUser.setNickName(wui.getNickName());
					newUser.setHeadImgUrl(wui.getHeadImgUrl());
					newUser.setCountry(wui.getCountry());
					newUser.setCity(wui.getCity());
					newUser.setName(wui.getNickName()+" ");
					userDao.save(newUser);
					userId=newUser.getId()+"";
				}else{
					for (UserInfo userInfo : sssd) {
						
						if(userInfo.getOpenid()!=null&&userInfo.getId()!=null){
							//每次登陆都重新设置一次用户信息
							userInfo.setPwd("123456");
							userInfo.setOpenid(wui.getOpenId());
							userInfo.setNickName(wui.getNickName());
							userInfo.setHeadImgUrl(wui.getHeadImgUrl());
							userInfo.setCountry(wui.getCountry());
							userInfo.setCity(wui.getCity());
							userInfo.setName(wui.getNickName()+" ");
							userDao.save(userInfo);
							userId=userInfo.getId()+"";
							break;
						}
					}
				}
				result.put(UserPackage.DATA, jsson);
				result.put(UserPackage.TICKET, JFUserAuthentication.getAticket(userId));
				result.put(UserPackage.STATUS, "200");
				return result.toString();
			} catch (Exception e) {
				e.printStackTrace();
				result.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
				return result.toString();
			}
		}
		return result.toString();
	}
	@RequestMapping("/getall")
	public String getallUser(){
		JSONObject json=new JSONObject();
		try {
			 List<UserInfo> userarr=(List<UserInfo>) userDao.findAll();
			 JSONArray array=new JSONArray();
			 userarr.stream().forEach(item->{
				 JSONObject tjson=BeanUtils.getAJsonFromObj(item, null);
				 tjson.remove("pwd");
				 array.put(tjson);
			 });
			 json.put(UserPackage.STATUS, "200");
			 json.put(UserPackage.DATA, array);
		} catch (Exception e) {
			e.printStackTrace();
			json.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
		}
		return json.toString();
	}
	@RequestMapping("/getmain")
	public String getMainUser(){
		JSONObject json=new JSONObject();
		try {
			 List<UserInfo> userarr=(List<UserInfo>) userDao.findAll();
			 JSONArray array=new JSONArray();
			 userarr.stream().forEach(item->{
				 JSONObject tjson=BeanUtils.getAJsonFromObj(item, new String[]{"id","nickName"});
				 array.put(tjson);
			 });
			 json.put(UserPackage.STATUS, "200");
			 json.put(UserPackage.DATA, array);
		} catch (Exception e) {
			e.printStackTrace();
			json.put(UserPackage.STATUS, UserPackage.SERVER_ERROR);
		}
		return json.toString();
	}
}
